package com.ctz.commonframe.utils;

import java.io.File;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.widget.Toast;

public class SDCardUtil {
	public enum Unit{
		BYTE, KB, MB;
	}
	
	/**
	 * 判断sd是否存在
	 * 
	 * @return
	 */
	public static boolean isSDCardExist() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}
	
	/**
	 * 获取sd卡路径
	 * @param context
	 * @return
	 */
	public static String getSDCardPath(Context context){
		if(!isSDCardExist()){
			Toast.makeText(context, "sd卡不存在", Toast.LENGTH_SHORT).show();
			return null;
		}else if(getSDFreeSize(Unit.MB) < 5){
			Toast.makeText(context, "sd卡空间不足", Toast.LENGTH_SHORT).show();
			return null;
		}else{
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		}
	}

	/**
	 * 返回SD卡空闲大小，单位MB
	 * 
	 * @param unit 单位
	 * @return
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	@SuppressLint("NewApi")
	public static long getSDFreeSize(Unit unit) {
		File path = Environment.getExternalStorageDirectory();
		StatFs sf = new StatFs(path.getPath());
		// 获取单个数据块的大小(Byte)
		long blockSize = sf.getBlockSizeLong();
		// 空闲的数据块的数量
		long freeBlocks = sf.getAvailableBlocksLong();
		switch (unit) {
		case BYTE:
			return freeBlocks * blockSize; 
		case KB:
			return (freeBlocks * blockSize)/1024;
		case MB:
			return (freeBlocks * blockSize) / 1024 / 1024;
		}
		return 0;
	}

	/**
	 * 获取SD卡总大小，单位MB
	 * 
	 * @param unit 单位
	 * @return
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	@SuppressLint("NewApi")
	public static long getSDAllSize(Unit unit) {
		File path = Environment.getExternalStorageDirectory();
		StatFs sf = new StatFs(path.getPath());
		long blockSize = sf.getBlockSizeLong();
		long allBlocks = sf.getBlockCountLong();
		switch (unit) {
		case BYTE:
			return allBlocks * blockSize; 
		case KB:
			return (allBlocks * blockSize)/1024;
		case MB:
			return (allBlocks * blockSize) / 1024 / 1024;
		}
		return 0;
	}
	
}
